import { t } from 'i18next'
import { Button, CheckBox, Modal, RadioGroup, Space } from '@kedacom/react-next'
import { useEffect, useRef, useState } from 'react'
import VmpView from './VmpView'
import { ViewRef } from './VmpView/interface'
import { useAutoVmpStore } from './store'
import { StyledWrap } from './style'
import MemberList from '../../../components/MemberList'
import { useBasicInfoStore } from '../../basicInfo/store'
import { VmpEntity } from '../interface'
import shallow from 'zustand/shallow'
import { useMeetingTVWallStore } from '../store'
import { useGlobalStore } from '@/store/global'

export default function AutoVmpDialog() {
	const { superMtNum } = useBasicInfoStore.getState()
	const { isOpen, mode, data, update, updateData, onInit, onClose, onConfirm } = useAutoVmpStore((state) => ({
		isOpen: state.isOpen,
		mode: state.mode,
		data: state.data,
		update: state.update,
		updateData: state.updateData,
		onInit: state.onInit,
		onClose: state.onClose,
		onConfirm: state.onConfirm,
	}))
	const { updateMeetingTvwallStore, correct_style_operate_box_info, operate_correct_style_info, correct_style } =
		useMeetingTVWallStore(
			(state) => ({
				updateMeetingTvwallStore: state.update,
				correct_style_operate_box_info: state.correct_style_operate_box_info,
				show_mt_name: state.show_mt_name,
				operate_correct_style_info: state.operate_correct_style_info,
				correct_style: state.correct_style,
			}),
			shallow
		)
	const [isModify, setIsModify] = useState(false)
	// const loadMaskRef = useRef<any>(null)
	const viewRef = useRef<ViewRef | null>(null)
	// const mtid = mtInfo?.mtid ?? ''
	// const { run } = useRequest(() => fetchGetMtVmpParam(meetingMoid, mtid), {
	// 	manual: true,
	// 	onSuccess: (res) => {
	// 		loadMaskRef.current?.hide() //隐藏蒙层
	// 		if (res && res.success) {
	// 			let _data = transMtVmpParam(res.data)
	// 			//获取接口不给state值，res.data为null是未开启，有值是开启
	// 			updateData({ ..._data, state: res.data ? 1 : 0 })
	// 		} else {
	// 			handleClose()
	// 			Alert(t('获取终端自主多画面信息失败'))
	// 		}
	// 	},
	// })
	// useEffect(() => {
	// 	if (isOpen) {
	// 		onInit()
	// 	}
	// }, [isOpen])
	useEffect(() => {
		if (correct_style_operate_box_info) {
			let _source = operate_correct_style_info[correct_style]?.members ?? []
			/**四分屏数据*/
			let _vmp = _source.find(
				(item) => item.member_type === 8 && item.hdu_id === correct_style_operate_box_info
			)?.vmp
			if (_vmp) {
				update({ data: _vmp })
				return
			} else {
				update({
					data: {
						name: '',
						mode: 2,
						show_mt_name: 1,
						layout: 0,
						members: [],
					},
				})
			}
		} else {
			update({
				data: {
					name: '',
					mode: 2,
					show_mt_name: 1,
					layout: 0,
					members: [],
				},
			})
			return
		}
	}, [correct_style_operate_box_info, isOpen])
	// useEffect(() => {
	// 	store.setState({
	// 		msgHandle: (vmpData) => {
	// 			if (mode !== 'mtVmp' || isModify || vmpData.vmp_mt.mt_id !== mtid) return
	// 			if (vmpData.state === 0) {
	// 				updateData({ ...data, state: 0 })
	// 			} else {
	// 				let _data = transMtVmpParam(vmpData)
	// 				updateData(_data)
	// 			}
	// 		},
	// 	})
	// }, [mode, isModify, mtid, updateData])
	const handleClose = () => {
		update({ isOpen: false })
		onClose?.()
	}
	const getParam = (): VmpEntity => ({
		name: '',
		mode: data.mode,
		show_mt_name: data.show_mt_name,
		layout: data.mode === 2 ? 0 : viewRef.current?.getStyle() ?? 0,
		members:
			data.mode === 2
				? []
				: viewRef.current?.getValue().map((item) => ({
						account: item.account ?? '',
						account_type: item.account_type ?? 1,
						name: item.name ?? '',
						chn_idx: item.chn_idx,
						member_type: 1,
						conf_e164: item.conf_e164 ?? '',
				  })) ?? [],
	})
	/**设置缓存*/
	const setCash = () => {
		let param = getParam()
		let source = {}
		/**找到当前通道对应的盒子*/
		let member = operate_correct_style_info[correct_style]?.members || []
		/**判断当前通道是否已有缓存*/
		let flag = member?.some((item) => {
			return item.hdu_id === correct_style_operate_box_info
		})
		if (flag) {
			/**已存在缓存*/
			for (let i = 0; i < member.length; i++) {
				if (member[i].hdu_id === correct_style_operate_box_info) {
					member[i] = {
						member_type: 8,
						vmp: param,
						hdu_id: correct_style_operate_box_info,
					}
				}
			}
		} else {
			/**不能找到新增*/
			member?.push({
				member_type: 8,
				vmp: param,
				hdu_id: correct_style_operate_box_info,
			})
		}
		source = Object.assign({}, operate_correct_style_info[correct_style], { members: member })
		operate_correct_style_info[correct_style] = source
		updateMeetingTvwallStore({ operate_correct_style_info: operate_correct_style_info })
	}
	const handleOk = () => {
		setCash()
		handleClose()
	}
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	return (
		<Modal
			className="auto-vmp-dialog"
			open={isOpen}
			width={858}
			height={535}
			title={t('自主多画面')}
			needFooter={false}
			onCancel={handleClose}
		>
			<StyledWrap>
				<div className="content">
					<div className="view">
						<div className="mode-wrap">
							<span className="label">{t('模式选择')}</span>
							<RadioGroup
								value={data.mode}
								options={[
									{ label: t('自动自主多画面'), value: 2, width: 140 },
									{ label: t('定制画面合成'), value: 1, width: 140 },
								]}
								onChange={(e, val) => {
									setIsModify(true)
									let _data = { ...data }
									if (val === 1) {
										_data.mode = 1
										_data.layout = 5
									} else {
										_data.mode = 2
										_data.layout = 0
									}
									_data.members = []
									updateData(_data)
								}}
							></RadioGroup>
						</div>
						{data.mode === 2 && <div className="dynamic-view">{t('自动')}</div>}
						{data.mode === 1 && (
							<VmpView
								ref={viewRef}
								style={data.layout}
								members={data.members}
								onSelect={() => {
									setIsModify(true)
								}}
								onBoxChange={() => {
									setIsModify(true)
								}}
							/>
						)}
					</div>
					{data.mode === 1 && (
						<div className="list">
							<MemberList height={superMtNum || !SWITCH.showOftenMt ? 370 : 348} />
						</div>
					)}
				</div>
				<div className="bottom">
					<div className="left-wrap">
						<CheckBox
							checked={Boolean(data.show_mt_name)}
							onChange={(e, val) => {
								setIsModify(true)
								updateData({ ...data, show_mt_name: val ? 1 : 0 })
							}}
						>
							{t('显示终端名称')}
						</CheckBox>
						<span className="tip">
							<span className="icon"></span>
							{t('请拖拽与会方至指定的画面中')}
						</span>
					</div>
					<Space className="right-wrap">
						<Button className="confirm" width={80} onClick={handleOk}>
							{t('确认')}
						</Button>
						<Button className="cancel" width={80} onClick={handleClose}>
							{t('取消')}
						</Button>
					</Space>
				</div>
			</StyledWrap>
		</Modal>
	)
}
